package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.S_CROSS_UNION_SYNC_FROM_CROSS, desc = "区服请求跨服全量数据/返回")
public class RequestCrossUnionDataCmdFromCross implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        CrossUnionProto.RequestCrossUnionDataRespMsg respMsg = CrossUnionProto.RequestCrossUnionDataRespMsg.parseFrom(packet.getBytes());

        CrossUnionMgr.getLogger().debug("packet size {}", packet.getBytes().length);

        CrossUnionMgr.getLogger().debug("time : {}", System.currentTimeMillis());

        Map<String, Map<Long, CrossUnionMember>> tempUnionMemberMap = new ConcurrentHashMap<>();
        for (CrossUnionProto.CrossUnionMemberTemp temp : respMsg.getAllMemberList()) {
            CrossUnionMember member = CrossUnionPb.parseCrossUnionMember(temp);
            if (StringUtils.isNullOrEmpty(member.getUnionUid())) {
                CrossUnionMgr.getDeleteUnionMemberMap().put(member.getUserId(), member);
            } else {
                Map<Long, CrossUnionMember> map = tempUnionMemberMap.get(member.getUnionUid());
                if (map == null) {
                    map = new ConcurrentHashMap<>();
                    tempUnionMemberMap.put(member.getUnionUid(), map);
                }
                map.put(member.getUserId(), member);
            }
        }
        CrossUnionMgr.getUnionMemberMap().putAll(tempUnionMemberMap);

        for (CrossUnionProto.CrossUnionTemp temp : respMsg.getAllUnionList()) {
            CrossUnionInfo unionInfo = CrossUnionPb.parseCrossUnionInfo(temp);
            if (unionInfo.isDelete()) {
                CrossUnionMgr.getDeleteUnionInfoMap().put(unionInfo.getUnionUid(), unionInfo);
            } else {
                CrossUnionMgr.getUnionInfoMap().put(unionInfo.getUnionUid(), unionInfo);
            }
        }

        CrossUnionMgr.setAllSync(true);
        CrossUnionMgr.getLogger().debug("time : {}", System.currentTimeMillis());

        //初始商会榜单（本服）
        RankMgr.initUnionRankListModel();
    }
}
